package com.clss.commandhelper.view;

import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.widget.TextView;

/**
 * Created by Administrator on 2017/6/3.
 * 设置textview数字格式为00:00,并进行倒计时
 */

public class CountDownTextView extends TextView implements Runnable {

    private boolean run = false; //觉得是否执行run方法
    private int time;
    private int totalTime;
    private int type = 0;

    public CountDownTextView(Context context) {
        super(context);
    }

    public CountDownTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }
    public void setType(int type){
        this.type = type;
    }

    public void setTime(int time){  //设定初始值
        this.time = time;
        this.totalTime = time;
        if (type == 0){
//            if ((time/60) < 10)
            this.setText(time / 60 + ":" + time % 60);
        }else if (type == 1){
            if (time/60 != 0){
                this.setText(time / 60+"′"+time % 60+"″");
            }else {
                this.setText(time % 60 + "″");
            }
        }
    }
    public boolean isRun(){
        return run;
    }
    public void beginRun(){
        this.run = true;
        time +=1;
        run();
    }
    public void stopRun(){
        this.run = false;
//        this.setText(totalTime / 60 + ":" + totalTime % 60);

        if (type == 0){
            this.setText(time / 60 + ":" + time % 60);
        }else if (type == 1){
            if (time/60 != 0){
                this.setText(time / 60+"′"+time % 60+"″");
            }else {
                this.setText(time % 60 + "″");
            }
        }
    }

    @Override
    public void run() {
        if (run){
            ComputeTime();

//            this.setText(time / 60 + ":" + time % 60);

            if (type == 0){
                this.setText(time / 60 + ":" + time % 60);
            }else if (type == 1){
                if (time/60 != 0){
                    this.setText(time / 60+"′"+time % 60+"″");
                }else {
                    this.setText(time % 60 + "″");
                }
            }

            postDelayed(this, 1000);



        }else{
            removeCallbacks(this);
        }
    }

    private void ComputeTime(){
        time--;
        if (time==0)
            stopRun();
    }
}
